package com.yuju.controller.alipay;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayOpenAuthTokenAppRequest;
import com.alipay.api.response.AlipayOpenAuthTokenAppResponse;
import com.yuju.controller.base.BaseController;
import com.yuju.util.ConfigUtil;
import com.yuju.util.Utils;

/**
 * 
 * 类名：AlipayController  <br />
 *
 * 功能：Alipay接口
 *
 * @author : xuehj <br />
 * @Date : 2018年1月27日 下午4:05:25  <br />
 * @version : 1.1 <br />
 */
@Controller
@RequestMapping("alipay")
public class AlipayController extends BaseController {
	
	@RequestMapping("callback")
	public void alipayCallback() {
		System.out.println("支付宝回调接口");
		String authCode = getRequest().getParameter("app_auth_code");
		if (Utils.isNotNull(authCode)) {
			getAppAuthCode();
		} else {
			String body = getRequest().getParameter("body");
			String out_trade_no = getRequest().getParameter("out_trade_no");
			String trade_status = getRequest().getParameter("trade_status");
			String app_id = getRequest().getParameter("app_id");
			String total_amount = getRequest().getParameter("total_amount");
			String buyer_id = getRequest().getParameter("buyer_id");
			String trade_no = getRequest().getParameter("trade_no");
			String open_id = getRequest().getParameter("open_id");
			String buyer_logon_id = getRequest().getParameter("buyer_logon_id");
			String memuuid = getRequest().getParameter("memuuid");
			String memcode = getRequest().getParameter("memcode");
			System.out.println(out_trade_no);
			System.out.println(trade_status);
			if ("TRADE_SUCCESS".equals(trade_status)) {
				System.out.println("支付成功");
			} else {
				System.out.println("支付失败");
			}
		}
	}
	
	public void getAppAuthCode() {
		ConfigUtil.init("zfbinfo.properties");
		String appId = ConfigUtil.get("appid");
		String appPrivateKey = ConfigUtil.get("private_key");
		String alipayPublicKey = ConfigUtil.get("alipay_public_key");
		String appAuthCode = getRequest().getParameter("app_auth_code");
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, appPrivateKey, "json", "utf-8", alipayPublicKey, "RSA2");
		AlipayOpenAuthTokenAppRequest request = new AlipayOpenAuthTokenAppRequest();
		request.setBizContent("{" +
		"    \"grant_type\":\"authorization_code\"," +
		"    \"code\":\""+getRequest().getParameter("app_auth_code")+"\"" +
		"  }");
		try {
			AlipayOpenAuthTokenAppResponse response = alipayClient.execute(request);
			response.getAppAuthToken();
			System.out.println(response.getAppAuthToken());
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
